package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Wrapper;
import java.util.Date;
import java.util.List;

/**
 * Package: com.heima.wemedia.service.impl
 * ClassName: WmMaterialServiceImpl
 * Description:
 *
 * @Author : 福森森
 * @Create : 2024/8/27 12:10
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minIO中
        //获取后缀
        String postfix = StrUtil.subAfter(multipartFile.getOriginalFilename(), '.', true);
        //拼接(重命名文件)
        String fileName = StrUtil.format("{}.{}", IdUtil.simpleUUID(), postfix);
        //文件url
        String url;
        try {
            //上传到minio中并获取其url
            url = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，URL:{}", url);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl-上传文件失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传文件失败");
        }

        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public PageResponseResult<List<WmMaterial>> search(WmMaterialDto wmMaterialDto) {
        wmMaterialDto.checkParam();

        IPage<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //条件一：是否收藏
        lambdaQueryWrapper.eq(ObjectUtil.equal(wmMaterialDto.getIsCollection(), 1), WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //查询数据
        super.page(page, lambdaQueryWrapper);
        //返回结果
        return PageResponseResult.<List<WmMaterial>>builder()
                .currentPage(wmMaterialDto.getPage())
                .size(wmMaterialDto.getSize())
                .total(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    @Override
    public ResponseResult<Void> delPicture(Integer id) {
        //校验参数
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //构建查询条件
        LambdaQueryChainWrapper<WmMaterial> wrapper = lambdaQuery().eq(WmMaterial::getId, id);
        //校验查询结果，为空则数据不存在
        if (ObjectUtil.isEmpty(wrapper.one())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除并校验删除是否成功
        if (!this.removeById(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件删除失败");
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult<Void> cancelCollect(Integer id) {
        //校验参数
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean update = lambdaUpdate().set(WmMaterial::getIsCollection, Convert.toShort(0)).eq(WmMaterial::getId,id).update();
        if (!update) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "取消收藏失败");
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult<Void> collect(Integer id) {
        //校验参数
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean update = lambdaUpdate().set(WmMaterial::getIsCollection, Convert.toShort(1)).eq(WmMaterial::getId,id).update();
        if (!update) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "收藏失败");
        }
        return ResponseResult.okResult(null);
    }


}
























